const db = require('../db/index')

exports.getArticleCates = (req,res) => {
  const slq = 'select * from ev_article_cate where is_delete = 0 order by id asc'

  db.query(slq,(err,results) => {
    if(err) return res.cc(err) 
      
    res.send({
      status:0,
      message:'获取文章分类列表成功',
      data:results
    })
  })
}

exports.addArticleCates = (req,res) => {
  const sqlStr = 'select * from ev_article_cate where name = ? or alias = ?'

  db.query(sqlStr,[req.body.name,req.body.alias],(err,results) => { 
    if(err) return res.cc(err)

    if(results.length === 2) return res.cc('分类名称与别名被占用，请更换后重试！')
    if(results.length === 1 && results[0].name === req.body.name && results[0].alias === req.body.alias) return res.cc('分类名称与别名被占用，请更换后重试！')
    if(results.length === 1 && results[0].name === req.body.name) return res.cc('分类名称被占用，请更换后重试！')
    if(results.length === 1 && results[0].alias === req.body.alias) return res.cc('分类别名被占用，请更换后重试！')

    const sqlStr = 'insert into ev_article_cate set ?'
    db.query(sqlStr,req.body,(err,results) => {
      if(err) return res.cc(err)
      if(results.affectedRows !== 1) return res.cc('新增文章分类失败')
      
      res.cc('新增文章分类成功',0)
    })
  })
}

exports.deleteCateById = (req,res) => {
  const sqlStr = 'update ev_article_cate set is_delete = 1 where id = ?'
  db.query(sqlStr,req.params.id,(err,result) => {
    if(err) return res.cc(err)
    if(result.affectedRows !== 1) return res.cc('删除文章分类失败！')

    res.cc('删除文章分类成功',0)
  })
}

exports.getArtCateById = (req,res) => {
  const sqlStr = 'select * from ev_article_cate where id = ?'

  db.query(sqlStr,req.params.id,(err,result) => {
    if(err) return res.cc(err)
    if(result.length !== 1) return res.cc('获取文章分类数据失败')

    res.send({
      status:0,
      message:'获取文章分类数据成功',
      data:result[0]
    })
  })
}

exports.updateCateById = (req,res) => {
  // 执行查重操作
  db.query(sql,[req.body.id,req.body.name,req.body.alias],(err,result) => {
    // 执行 SQL 语句失败
    if(err) return res.cc(err)

    // 分类名称 和 分类别名 都被占用
    if(result.length === 2) return res.cc('分类名称与分类别名被占用，请更换后重试')
    if(result.length === 1 && result[0].name === req.body.name && result[0].alias === req.body.alias) return 
    res.cc('分类名称与分类别名被占用，请更换后重试')
    if(result.length === 1 && result[0].name === req.body.name) return res.cc('分类名称被占用，请更换后重试')
    if(result.length === 1 && retult[0].alias === req.body.alias) return res.cc('分类别名称被占用，请更换后重试')

    const sqlStr = 'update ev_article_cate set ? where id = 1'

    db.query(sqlStr,[req.body,req.body.id],(err,result) => {
      if(err) return res.cc(err)
      if(result.affectedRows !== 1) return res.cc('更新文章分类失败')
      
      res.cc('更新文章分类成功',0)
    })
  })
}